/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.web.actions.usuarios;

import com.ejemplo.bt.monedas.services.MonedaServices;
import com.ejemplo.bt.monedas.vo.Moneda;
import com.web.actions.AbstractAction;
import com.web.actions.usuarios.vo.MonedaEditorActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author Usuario
 */
public class DoSalvarMonedaAction extends AbstractAction {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
       
        MonedaEditorActionForm formu = (MonedaEditorActionForm) request.getSession().getAttribute("datosValidados");

        if (formu == null){
        formu = (MonedaEditorActionForm) form;
        }
        ActionErrors errors = new ActionErrors();

        try {

        // Obtengo el provider de monedas
        MonedaServices services = new MonedaServices();

        Moneda moneda = new Moneda();

        if(formu.getIdMoneda() != 0) {
            moneda = services.obtenerMoneda(formu.getIdMoneda());
            moneda.setMoneda(formu.getMoneda());
            services.salvarMoneda(moneda);
            return mapping.findForward("success");
        }

        if(formu.getIdMoneda()==0){
            moneda.setMoneda(formu.getMoneda());
            services.salvarMoneda(moneda);
        }else{
            return mapping.findForward("failure");
        }
        // Forwardeo.
        return mapping.findForward("success");
        }
        catch (Exception ex) {
        ex.printStackTrace();
        // Salvo los errores en el request.
        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.message",
            ex.getMessage()));
        saveErrors(request, errors);

        // Salvo los datos validados en caso de que se de un error
        request.setAttribute("datosValidados", form);

        // Forwardeo.
        return mapping.findForward("failure");
        }
    }
}
